/* 
 * Copyright 2011 Steffen Schäfer
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package de.richsource.gwtplug.client;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;

/**
 * Registry to access plugins and exported components.
 * 
 * @author Steffen Schäfer
 *
 */
class PluginRegistry extends JavaScriptObject {

	protected PluginRegistry() {
	}

	static native PluginRegistry get() /*-{
		if (!$wnd.gwtPlugRegistry) {
			$wnd.gwtPlugRegistry = new Object();
			$wnd.gwtPlugRegistry.plugins = [];
			$wnd.gwtPlugRegistry.registeredComponents = [];
		}
		return $wnd.gwtPlugRegistry;
	}-*/;

	final void add(PluginComponentManager pluginComponentManager) {
		getPlugins().push(pluginComponentManager);
		// read all already registered components
		readAllRegisteredcomponents();
	};

	final void addComponent(JavaScriptObject component) {
		JsArray<PluginComponentManager> plugins = getPlugins();
		for (int i = 0; i < plugins.length(); i++) {
			PluginComponentManager pluginComponentManager = plugins.get(i);
			if (pluginComponentManager.equals(PluginComponentManager
					.getInstance())) {
				// do not notify this plugin.
				continue;
			}
			pluginComponentManager.callHandleNewComponent(component);
		}
		addComponentsToRegistry(component);
	};

	private final native void addComponentsToRegistry(JavaScriptObject component) /*-{
		this.registeredComponents.push(component);
	}-*/;

	private final native JsArray<PluginComponentManager> getPlugins() /*-{
		return this.plugins;
	}-*/;

	private native JsArray<JavaScriptObject> getRegisteredComponents() /*-{
		return this.registeredComponents;
	}-*/;

	private void readAllRegisteredcomponents() {
		JsArray<JavaScriptObject> registeredComponents = getRegisteredComponents();
		for (int i = 0; i < registeredComponents.length(); i++) {
			JavaScriptObject component = registeredComponents.get(i);
			if(component== null) {
				continue;
			}
			PluginComponentManager.handleNewComponent(component);
		}
	};

}
